package com.qutan.app.core.manager;

import com.alibaba.dubbo.config.annotation.Service;
import com.i7time.entity.FriendInfo;
import com.i7time.service.FriendService;
import com.qutan.app.core.cache.FriendCache;
import com.qutan.app.core.cache.UserCache;
import com.qutan.app.core.domain.Friend;
import com.qutan.app.core.domain.UserInfo;
import com.qutan.app.core.repository.FriendRepository;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Created by pengweiyuan on 6/21/16.
 */
@Service(version = "1.0.0", interfaceClass = FriendService.class)
public class FriendManager implements FriendService {

    private static Logger logger = org.slf4j.LoggerFactory.getLogger(FriendManager.class);

    @Autowired
    private FriendRepository friendRepository;

    @Autowired
    private UserCache userCache;

    @Autowired
    private FriendCache friendCache;

    @Override
    public List<FriendInfo> getFriendList(long userId) {
        List<FriendInfo> friendInfos=friendCache.getFriendListByUserId(userId);
        if(friendInfos!=null){
            System.err.println(">>>>>>>>friend from redis");
            return friendInfos;
        }
        System.err.println("userId="+userId);
        List<Friend> friends = friendRepository.findByUserId(userId);
        if (friends.isEmpty()) return new ArrayList<>();
        List<FriendInfo> resultList = new ArrayList<>();
        friends.forEach(friend -> {
            resultList.add(friend.convert2FriendInfo());
        });
        friendCache.setFriendCache(userId,resultList);
        return resultList;
    }

    @Override
    public boolean addFriend(long userId, long targetId) {
        UserInfo targetInfo = userCache.getUserInfoCheckDbById(targetId);
        if (targetInfo == null){
            logger.warn("addFriend targetInfo =null id={}",targetId);
            return  false;
        }

        Friend andFriendId = friendRepository.findByUserIdAndFriendId(userId, targetId);
        if(andFriendId!=null){
            return false;
        }
        Friend friend=new Friend();
        friend.setFriendAvatar(targetInfo.getAvatar());
        friend.setFriendNickName(targetInfo.getNick_name());
        friend.setUserId(userId);
        friend.setFriendId(targetId);
        friend.setSex(targetInfo.getSex());
        Friend save = friendRepository.save(friend);
        friendCache.addFriendByUserIdAndFriendId(userId,save.convert2FriendInfo());
        return true;
    }

    /**
     * 加入黑名单
     * @param userId 用户ID
     * @param targetId 目标ID
     * @return
     */
    @Override
    public boolean toBlackList(long userId, long targetId) {
        try{
            Friend friend =friendRepository.findByUserIdAndFriendId(userId,targetId);
            if(friend==null){
                logger.warn("toBlackList warn friend==null,id={},targetId={}",userId,targetId);
                return false;
            }
            if(friend.getBlackList().contains(targetId)){
                return  false;
            }
            friend.getBlackList().add(targetId);
            friendRepository.delete(friend.getId());
            return true;
        }catch (Exception e){
            logger.error("toBlackList error,id={},targetId={}",userId,targetId,e);
            return false;
        }
    }

    @Override
    public boolean deleteFriend(long userId, long targetId) {
        try{
            Friend friend =friendRepository.findByUserIdAndFriendId(userId,targetId);
            if(friend==null){
                logger.warn("deleteFriend warn friend==null,id={},targetId={}",userId,targetId);
                return false;
            }
            friendRepository.delete(friend.getId());
            friendCache.removeFriendByUserIdAndFriendId(userId,targetId);
            return true;
        }catch (Exception e){
            logger.error("deleteFriend error,id={},targetId={}",userId,targetId,e);
            return false;
        }
    }

    @Override
    public boolean modifyFriendNickName(long userId, long targetId, String nickName) {
        try{
            Friend friend =friendRepository.findByUserIdAndFriendId(userId,targetId);
            if(friend==null){
                logger.warn("modifyFriendNickName warn friend==null,id={},targetId={}",userId,targetId);
                return false;
            }
            friend.setFriendNickName(nickName);
            friendRepository.save(friend);
            friendCache.deleteFrinedByUserId(userId);
            return true;
        }catch (Exception e){
            logger.error("modifyFriendNickName error,id={},targetId={}",userId,targetId);
            return false;
        }
    }

    @Override
    public FriendInfo getFriendById(long userid, long friendid) {
        try{
            Optional<FriendInfo> friendInfoById = friendCache.getFriendInfoById(userid, friendid);
            if(friendInfoById!=null&&friendInfoById.isPresent()){
                return  friendInfoById.get();
            }
            Friend friend = friendRepository.findByUserIdAndFriendId(userid, friendid);
            if(friend==null)
                return null;
            return friend.convert2FriendInfo();
        }catch (Exception e){
            logger.error("getFriendById error,id={},targetId={}",userid,friendid);
            return null;
        }
    }
}
